package com.qianfeng.zhangwei.camera;

import android.annotation.TargetApi;
import android.graphics.Bitmap;
import android.os.Build;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;

import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import com.lidroid.xutils.view.annotation.ContentView;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.lidroid.xutils.view.annotation.event.OnClick;
import com.qianfeng.zhangwei.camera.adapter.UploadAdapter;
import com.qianfeng.zhangwei.camera.bean.DividerItemDecoration;
import com.qianfeng.zhangwei.camera.bean.UploadImage;
import com.qianfeng.zhangwei.camera.linstener.OnItemClick;
import com.qianfeng.zhangwei.camera.utils.FileUtils;
import com.qianfeng.zhangwei.camera.utils.ImageUtils;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

/**
 * 第一步 显示拍照图片
 * 注意:
 * 1> 凡是操作sdk的文件或者数据都尽量不要在主线程中写
 * 2> 多选的时候注意图片错位的问题
 *
 * 上传图片 介绍服务器
 *
 * java 模拟form表单提交数据
 *
 *
 * Bitmap转化字符串给我传上来
 *
 * Base64转成字符串
 * 服务器在把字符串转化成图
 *
 * 显示的时候对图片进行二次采样
 * 上传到服务器 对图片进行压缩   质量压缩法
 */
@ContentView(R.layout.activity_upload)
public class UploadActivity extends AppCompatActivity implements OnItemClick {
    private String uploadUrl = "http://10.2.158.7:8080/app/uplaodFile?method=upload";
    @ViewInject(R.id.recyclerView)
    private RecyclerView recyclerView;
    private UploadAdapter adapter;
    private List<UploadImage> bitmapList = new ArrayList<>();
    @ViewInject(R.id.upload_file_btn)
    private Button uploadBtn;
    private ProgressBar progressBar;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ViewUtils.inject(this);
        getBitmaps();
        init();
    }

    /**
     * 初始化ui
     */
    private void init() {
        GridLayoutManager gridLayoutManager = new GridLayoutManager(this, 3, LinearLayoutManager.VERTICAL, false);
        recyclerView.setLayoutManager(gridLayoutManager);
        //添加分割线
        recyclerView.addItemDecoration(new DividerItemDecoration(this, DividerItemDecoration.VERTICAL_LIST));
        adapter = new UploadAdapter(bitmapList);
        adapter.setOnItemClick(this);
        recyclerView.setAdapter(adapter);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();
        if (id == R.id.upload_btn) {
            uploade();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    /**
     * 获取文件夹中的图片
     */
    @TargetApi(Build.VERSION_CODES.HONEYCOMB_MR1)
    private void getBitmaps() {
        File imageFile = new File(FileUtils.getPhotoPath());
        File[] files = imageFile.listFiles();
        if (files != null && files.length > 0) {
            for (File file : files) {
                Bitmap bitmap = ImageUtils.compressImageFromFile(file.getAbsolutePath(), 100, 100);
                if (bitmap != null && bitmap.getByteCount() > 0) {
                    bitmapList.add(new UploadImage(bitmap, false, file));
                }
            }
        } else {
//            byte[] imgByte = new byte[]{};
//            FileOutputStream fileOutputStream = new FileOutputStream("");
//            fileOutputStream.write(imgByte);
//            byte[] base64Data =  Base64.decode(imgByte, Base64.DEFAULT);
//            new String (base64Data);
        }
    }

    private void uploade() {
        HttpUtils httpUtils = new HttpUtils();
        final RequestParams params = new RequestParams();
        for (int i = 0; i < bitmapList.size(); i++) {
            if (bitmapList.get(i).isSelect()) {
                params.addBodyParameter("file" + i, bitmapList.get(i).getFile());
            }
        }
        httpUtils.send(HttpRequest.HttpMethod.POST, uploadUrl, params, new RequestCallBack<String>() {
            @Override
            public void onStart() {
                super.onStart();
                progressBar = new ProgressBar(UploadActivity.this);
            }

            @Override
            public void onLoading(long total, long current, boolean isUploading) {
                super.onLoading(total, current, isUploading);
                if (isUploading) {
                    progressBar.setMax((int) total);
                    progressBar.setProgress((int) current);
                    progressBar.setVisibility(View.VISIBLE);
                }


            }

            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {
                progressBar.setVisibility(View.GONE);
            }

            @Override
            public void onFailure(HttpException e, String s) {
                progressBar.setVisibility(View.GONE);
            }
        });


    }


    @Override
    public void onItemClick(int postion, UploadAdapter.UploadViewHolder vh) {
        UploadImage uploadImage = bitmapList.get(postion);
        if (uploadImage.isSelect()) {
            uploadImage.setIsSelect(false);
            vh.uploadCheckBox.setChecked(false);
        } else {
            uploadImage.setIsSelect(true);
            vh.uploadCheckBox.setChecked(true);
        }
    }

    @OnClick(R.id.upload_file_btn)
    public void uploadClick(View view) {
        uploade();
    }


}
